$(function() {

	if ($("#bannerImage").length > 0) {
		var bannerImage = '//image.faxsun.com' + $('#bannerUrl').val();

		if (bannerImage == null || bannerImage == '') {
			// 初始化封面图片
			$("#bannerImage").fileinput({
				uploadUrl : "/faxsun-info/admin/banners/upload", // server
				// upload
				// action
				uploadAsync : true,
				minFileCount : 1,
				maxFileCount : 1
			});
		} else {
			bannerImage = bannerImage + '!200x60';
			$("#bannerImage")
					.fileinput(
							{
								uploadUrl : "/faxsun-info/admin/banners/upload", // server
								// upload
								// action
								uploadAsync : true,
								minFileCount : 1,
								maxFileCount : 1,
								initialPreview : [
										"<img src='"
												+ bannerImage
												+ "' class='file-preview-image' alt='cover' title='cover'>", ],
							});
		}
	}

	$('#bannerImage').on('fileuploaded',
			function(event, data, previewId, index, jqXHR) {
				if (data.response.success) {
					$('#bannerUrl').val(data.response.infoMap.url);
				}
			});

	$('#bannerTable').on('click-row.bs.table', function(event, row, $element) {
		var url = "/faxsun-info/admin/banners/add?id=" + row.id;
		location.href = url;
	});

	// checkbox 选中事件
	$('#bannerTable').on('check.bs.table check-all.bs.table',
			function(event, rows) {
				// 选中频道设置isSelected为true
				postSelectedItems(rows, true);
			});

	// checkbox 选中事件
	$('#bannerTable').on('uncheck.bs.table uncheck-all.bs.table',
			function(event, rows) {
				// 选中频道设置isSelected为true
				postSelectedItems(rows, false);
			});

	$('#bannerform').on('submit', function(e) {
		e.preventDefault();
		$.ajax({
			url : $('#bannerform').attr('action'),
			method : "POST",
			data : $('#bannerform').serialize(),
			dataType: "json"
		}).success(function(data) {
			console.log(data.code);
			if(data.code==0){
				alert("banner保存成功");
				window.location.href="/faxsun-info/admin/banners/list";
			}
			else{
				alert("banner保存失败");
			}
		});
	});

	function postSelectedItems(rows, selected) {
		var content = "ids=" + getIdSelections(rows) + "&selected=" + selected;
		console.log(content);
		$.ajax({
			url : "/faxsun-info/admin/banners/setselected",
			method : "POST",
			data : content
		}).done(function(data) {
			// alert(data.message);
			$('#bannerTable').bootstrapTable('refresh', '');
			// TODO: 提示设置成功
		});
	}

	function getIdSelections(rows) {
		if (rows instanceof Array) {
			var idMap = $.map(rows, function(row) {
				return row.id
			});
			return idMap.join(',');
		} else {
			return rows.id;
		}
	}

});

// 格式化banner图片显示在列表中
function formatImage(value, row, index) {
	console.log(value);
	var imageElement = "<img height='60px' width='200px' src='//image.faxsun.com"
			+ value + "!200x60'/>";
	return imageElement;
}